package com.zhangyj.servlets;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zhangyj.util.Tools;

public class ValidateCodeServlet extends HttpServlet {
	private static final long serialVersionUID = -7565150789047304161L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("image/jpeg");
		String code = Tools.getValidateCode();
		HttpSession session = request.getSession();
		session.setAttribute(Tools.VALIDATE_KEY, code);
		createImage(response.getOutputStream(), code);
	}

	private void createImage(OutputStream out, String code) {
		int width = 60;
		int height = 20;
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = bi.createGraphics();
		g.setBackground(Color.WHITE);
		g.clearRect(0, 0, width, height);
		drawNoise(g, 10, width, height);
		g.setColor(Color.BLACK);
		drawText(g, code, 0, 20, 25);
		g.dispose();
		bi.flush();
		try {
			ImageIO.write(bi, "JPEG", out);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	public void drawNoise(Graphics2D graphics, int lineNumber, int width, int height)

	{
		graphics.setColor(Color.lightGray);

		for (int i = 0; i < lineNumber; i++)

		{

			int pointX1 = 1 + (int) (Math.random() * width);

			int pointY1 = 1 + (int) (Math.random() * height);

			int pointX2 = 1 + (int) (Math.random() * width);

			int pointY2 = 1 + (int) (Math.random() * height);

			graphics.drawLine(pointX1, pointY1, pointX2, pointY2);

		}

	}

	public void drawText(Graphics2D graphics, String text, int x, int y, int height)

	{
		graphics.setColor(Color.BLACK);
		Font font = graphics.getFont();
		Font newFont = new Font(font.getFontName(),font.getStyle(),height);
		graphics.setFont(newFont);
		graphics.drawString(text, x, y);
		graphics.setFont(font);
	}
}
